<template>
  <div ref="dropdownRef" class="dropdown" @click.prevent="handleShowClick">
    <a href="#" class="btn btn-outline-light my-2 dropdown-toggle">{{`你好 ${name}`}}</a>
    <ul
    class="dropdown-menu d-block" aria-labelledby="dropdownMenuButton1"
    v-if="isShow"
    >
        <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import useClickDropdown, { showClickFn } from '../hooks/useClickOutside'

export default defineComponent({
  name: 'Dropdown',
  props: {
    name: {
      type: String
    }
  },
  setup () {
    // 下拉菜单 dom 节点
    const dropdownRef = ref<null | HTMLElement>(null)
    // 下拉菜单 隐藏状态
    const isShow = ref(false)

    // 下拉菜单点击事件
    const { handleShowClick } = showClickFn(isShow)
    // 是在下拉菜单外点击还是在里面点击
    const isClickOutside = useClickDropdown(dropdownRef)
    // 监听点击判断
    watch(isClickOutside, () => {
      if (!isClickOutside.value && isShow.value) {
        isShow.value = false
      }
    })

    return { handleShowClick, isShow, dropdownRef }
  }
})
</script>
